/*
对打印Lodop控件 模版 封装
by gk
 */
(function ($) {
	$.printHTML = function (printUrl, strTaskName, reportId, extraParam) {
		initScript();
		printReportUrl(printUrl, strTaskName,reportId, extraParam);
		// 打印url
		// printUrl：请求路径（string）
		// strTaskName：打印任务名称（string）
		// reportId :报表的唯一key
		// extraParam：额外参数（string）
		function printReportUrl(printUrl, strTaskName, reportId, extraParam) {
			this.CLODOP = getLodop();
			var checkIds = getAllCheckedIds();
			if (checkIds == false) {
				return false;
			}
			
			if (extraParam == "home_barcode") {
				groupSize = checkIds.length;
			} else {
				var tmp = $("input[name='groupSize']").val();
				groupSize = tmp != undefined ? Number(tmp) : Number("${groupSize}");
			}
			extra = extraParam;
			var totalBatch = getTotalBatch(checkIds);
			print(printUrl,reportId, strTaskName, checkIds, 0, totalBatch);
		}
		// 获取所有选中项的 ID
		function getAllCheckedIds() {
			var idArr = [];
			$("input[class='chk']:checked").each(function () {
				idArr.push($(this).val());
			});
			if (idArr.length == 0) {
				layer.alert("请选择要打印的数据", {
					icon: 7,
					title: "提示"
				});
				return false;
			}
			return idArr;
		}
		// 同步方式打印
		// printUrl：请求路径（string）
		// reportId :报表的唯一key
		// mainTaskName：主任务名称（string）
		// allCheckedIds：存储所有选中项 ID 的数组（object）
		// batch：当前批次（number）
		// totalBatch：总批次（number）
		function print(printUrl,reportId, mainTaskName, allCheckedIds, batch, totalBatch) {
			var groupSize=5;
			var subIdArr = [];
			if ('' == "1" || '' == "1") {
				subIdArr = allCheckedIds;
			} else {
				if (batch + 1 < totalBatch) {
					for (var i = batch * groupSize; i < (batch + 1) * groupSize; i++) {
						subIdArr.push(allCheckedIds[i]);
					}
				} else {
					for (var i = batch * groupSize; i < allCheckedIds.length; i++) {
						subIdArr.push(allCheckedIds[i]);
					}
				}
			}
			//处置采用ajax获取打印的内容
			var pageJson = $("input[name='pageJson']").val();
			var data = {
				"path": reportId,
				"pageJson": pageJson,
				"groupSize": groupSize,
				"checkedIdStr": allCheckedIds,
				"extra": extra
			};
			var load = layer.load(2);
			$.ajax({
				url: printUrl,
				async: true,
				type: "post",
				data: JSON.stringify(data),
				contentType: "application/json",
				dataType: "text",
				success: function (result) {
					//利用jquery解析html标签
					$modal = $('<div>').html(result);
					var direction = $modal.find("#direction:first").val();
					var templates = $modal.find(".print_model");
					var paperName = $modal.find("#paperName:first").val();
					var zoom = $modal.find("#zoom:first").val();
					var paperWidth = $modal.find("#paperWidth:first").val();
					var paperHeight = $modal.find("#paperHeight:first").val();
					var tableRowThickNess = $modal.find("#tableRowThickNess:first").val();
					var printMode = $modal.find("#printMode:first").val();
					var qrPrefix = $modal.find("#qrPrefix").val();
					var groupSize = $modal.find("#groupSize:first").val();
					//设置参数
					// isPreview 是否预览
					// direction：方向（string，1：纵向 2：横向）
					// printUrl：请求路径（string）
					// mainTaskName：主任务名称（string）
					// allCheckedIds：存储所有选中项 ID 的数组（object）
					// batch：当前批次（number）
					// totalBatch：总批次（number）
					// paperName 纸张的名称( A3,A4,A5) 默认空字符串
					// pageWidth 纸张的宽度 自定义纸张需要值如 24mm 默认空字符串 优先最高,设置大小后纸张名称就无效
					// pageHeight 纸张的宽度 自定义纸张需要值如 80mm 默认空字符串 优先最高,设置大小后纸张名称就无效
					// zoom 报表的缩放大小 默认100%
					// tableRowThickNess 设定表格行的自动分页粒度 默认50
					var paperSetting = {
						isPreview:true,
						printUrl: printUrl,
						mainTaskName: mainTaskName,
						batch: batch,
						totalBatch: totalBatch,
						printMode: printMode ? printMode : 0,
						qrPrefix: qrPrefix ? qrPrefix : "#001:",
						direction: direction ? direction : 1,
						paperName: paperName ? paperName : "",
						paperWidth: paperWidth ? paperWidth : 0,
						paperHeight: paperHeight ? paperHeight : 0,
						zoom: zoom ? zoom : "100%",
						tableRowThickNess: tableRowThickNess ? tableRowThickNess : 50,
						AUTO_CLOSE_PREWINDOW: true,
						LANDSCAPE_DEFROTATED: true
					};
					//循环有多少批打印
					for (paperSetting.batch = 0; paperSetting.batch < totalBatch; paperSetting.batch++) {
						if (reportId == "asset/org/chuz/1") {
							createPageEx($modal, paperSetting);
						} else {
							createPage($modal, paperSetting);
						}
					}
				},
				error: function (result) {
					alert(result.responseText);
					layer.close(load);
				}
			});
		}
		function createPage($result, paperSetting) {
			var body=$result.html();
			var style = '<style>html{color:#000;background:#FFF}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td{white-space:nowrap;table-layout:fixed;overflow:hidden;margin:0;padding:0;word-break:break-all;}fieldset,img{border:0}input,select,textarea{outline:none}textarea{resize:none}a{text-decoration:none}table{border-collapse:collapse;border-spacing:0}address,caption,cite,code,dfn,em,th,var{font-style:normal;font-weight:normal}ol,ul{list-style:none}caption,th{text-align:left}</style>';
			this.CLODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", "<!DOCTYPE html>" + style + body);
			preview(paperSetting, true);
		}

		//paperSettings 打印设置
		//onPrintCallBack 打印时候触发
		function preview(paperSettings, onPrintCallBack) {
			// 子任务名称（主任务名称 + 当前批次）
			var subTaskName = paperSettings.mainTaskName + paperSettings.batch;
			// 打印子任务初始化
			this.CLODOP.PRINT_INIT(subTaskName);
			//设置打印缩放百分比
			this.CLODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT", paperSetting.zoom);
			//设置纸张大小
			this.CLODOP.SET_PRINT_PAGESIZE(paperSetting.direction, paperSetting.pageWidth, paperSetting.pageHeight, paperSetting.paperName);
			// 设定表格行的自动分页粒度
			this.CLODOP.SET_PRINT_STYLEA(0, "TableRowThickNess", paperSetting.tableRowThickNess);
			// 自动关闭预览窗口
			this.CLODOP.SET_PRINT_MODE("AUTO_CLOSE_PREWINDOW", paperSetting.AUTO_CLOSE_PREWINDOW);
			// 横向打印的预览默认旋转 90 度
			this.CLODOP.SET_SHOW_MODE("LANDSCAPE_DEFROTATED", paperSetting.LANDSCAPE_DEFROTATED);
			// C-Lodop 模式
			if (this.CLODOP.CVERSION) {
				this.CLODOP.On_Return_Remain = true;
				this.CLODOP.On_Return = function (TaskID, Value) {
					// 预览窗口关闭
					if (PreviewID == TaskID) {
						// 获取打印机名称
						GetValueID1 = this.CLODOP.GET_VALUE("PRINTSETUP_PRINTER_NAME", "selected");
						// 获取纸张名称
						GetValueID2 = this.CLODOP.GET_VALUE("PRINTSETUP_PAGESIZE_NAME", "selected");
						// 如果在预览界面发出了打印命令
						if (Value > 0) {
							printCallBack(paperSettings);
						}
					}
					// 打印成功
					if (PrintID == TaskID) {
						batch++;
						if (batch < paperSettings.totalBatch) {
							syncPrint(paperSettings.printUrl, paperSettings.mainTaskName, paperSettings.allCheckedIds, paperSettings.batch, paperSettings.totalBatch);
						}
					}
					// "获取打印机名称"函数返回
					if (GetValueID1 == TaskID) {
						printerName = Value;
					}
					// "获取纸张名称"函数返回
					if (GetValueID2 == TaskID) {
						paperName = Value;
					}
				}
				
				if (batch == 0) {
					// 首组任务执行时，显示预览界面
					PreviewID = this.CLODOP.PREVIEW();
				} else {
					// 指定打印机
					this.CLODOP.SET_PRINTER_INDEXA(printerName);
					// 后续任务执行时，直接打印
					PrintID = this.CLODOP.PRINT();
				}
				return;
			}
			// Lodop 模式
			else {
				if (batch == 0) {
					// 首组任务执行时，显示预览界面
					if (this.CLODOP.PREVIEW()) {
						// 获取在预览界面中选择的打印机名称
						printerName = this.CLODOP.GET_VALUE("PRINTSETUP_PRINTER_NAME", "selected");
						syncPrint(paperSettings.printUrl, paperSettings.mainTaskName, paperSettings.allCheckedIds, paperSettings.batch, totalBatch);
					}
				} else {
					// 指定打印机
					this.CLODOP.SET_PRINTER_INDEXA(printerName);
					// 后续任务执行时，直接打印
					if (this.CLODOP.PRINT()) {
						syncPrint(paperSettings.printUrl, paperSettings.mainTaskName, allCheckedIds, paperSettings.batch, paperSettings.totalBatch);
					}
				}
			}
		}
		//创建分页内容 by gk
		function createPageEx($result, paperSetting) {
			var $links = $result.find("link");
			var linksHtml = "";
			$links.each(function (index, element) {
				linksHtml = linksHtml + element.outerHTML;
			});
			var $styles = $result.find("style");
			var stylesHtml = "";
			$styles.each(function (index, element) {
				stylesHtml = stylesHtml + element.outerHTML;
			});
			var $tables = $result.find("table");
			$tables.each(function (index, element) {
				this.CLODOP.NewPageA();
				var tablehtml = linksHtml + stylesHtml + element.outerHTML;
				this.CLODOP.ADD_PRINT_TABLE("5mm", "5mm", "RightMargin:5mm", "BottomMargin:5mm", tablehtml);
			});
			preview(paperSetting, true);
		}
		//初始化
		function initScript() {
			//====页面引用CLodop云打印必须的JS文件：====
			if (needCLodop()) {
				var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
				//加了反向代理后的路径,这样只要一个路径就能
				var oscript = document.createElement("script");
				oscript.src = location.protocol + "//" + window.location.host + "/CLodopfuncs.js?priority=1";
				head.insertBefore(oscript, head.firstChild);
				//引用双端口(8000和18000）避免其中某个被占用：
				oscript = document.createElement("script");
				oscript.src = "http://localhost:8000/CLodopfuncs.js?priority=0";
				head.insertBefore(oscript, head.firstChild);
				//引用双端口(8000和18000）避免其中某个被占用：
				oscript = document.createElement("script");
				oscript.src = "http://localhost:18000/CLodopfuncs.js?priority=0";
				head.insertBefore(oscript, head.firstChild);
			};

		}

		//====获取LODOP对象的主过程：====
		function getLodop(oOBJECT, oEMBED) {
			var strHtmInstall = "<font color='#333'>打印控件未安装!点击这里<a href='/zl/static/plugin/lodop/install_lodop32.exe' target='_self' style='color:#FF00FF'>【执行安装】</a>,安装后请刷新页面或重新进入。</font>";
			var strHtmUpdate = "<font color='#333'>打印控件需要升级!点击这里<a href='/zl/static/plugin/lodop/install_lodop32.exe' target='_self' style='color:#FF00FF'>【执行升级】</a>,升级后请重新进入。</font>";
			var strHtm64_Install = "<font color='#333'>打印控件未安装!点击这里<a href='/zl/static/plugin/lodop/install_lodop64.exe' target='_self' style='color:#FF00FF'>【执行安装】</a>,安装后请刷新页面或重新进入。</font>";
			var strHtm64_Update = "<font color='#333'>打印控件需要升级!点击这里<a href='/zl/static/plugin/lodop/install_lodop64.exe' target='_self' style='color:#FF00FF'>【执行升级】</a>,升级后请重新进入。</font>";
			var strHtmFireFox = "<br><font color='#333'>（注意：如曾安装过Lodop旧版附件npActiveXPLugin,请在【工具】->【附加组件】->【扩展】中先卸它）</font>";
			var strHtmChrome = "<br><font color='#333'>(如果此前正常，仅因浏览器升级或重安装而出问题，需重新执行以上安装）</font>";
			var strCLodopInstall = "<font color='#333'>CLodop云打印服务(localhost本地)未安装启动!点击这里<a href='/zl/static/plugin/lodop/CLodop_Setup_for_Win32NT_https_2.129.exe' target='_self' style='color:#FF00FF'>【执行安装】</a>,安装后请刷新页面。</font>";
			var strCLodopUpdate = "<font color='#333'>CLodop云打印服务需升级!点击这里<a href='/zl/static/plugin/lodop/CLodop_Setup_for_Win32NT_https_2.129.exe' target='_self' style='color:#FF00FF'>【执行升级】</a>,升级后请刷新页面。</font>";
			var CreatedOKLodop7766 = null;
			try {
				var isIE = (navigator.userAgent.indexOf('MSIE') >= 0) || (navigator.userAgent.indexOf('Trident') >= 0);
				var is64IE = isIE && (navigator.userAgent.indexOf('x64') >= 0);
				if (needCLodop()) {
					try {
						this.CLODOP = getCLodop();
					} catch (err) {};
					if (!this.CLODOP && document.readyState !== "complete") {
						alert("C-Lodop没准备好，请稍后再试！");
						return;
					};
					if (!this.CLODOP) {
						if (isIE) {
							// document.write(strCLodopInstall);
							layer.alert(strCLodopInstall, {
								btn: [],
								icon: 0,
								title: "提示"
							});
						} else {
							// document.documentElement.innerHTML = strCLodopInstall + document.documentElement.innerHTML;
							layer.alert(strCLodopInstall, {
								btn: [],
								icon: 0,
								title: "提示"
							});
						}
						return;
					} else {
						if (CLODOP.CVERSION < "2.1.2.9") {
							if (isIE) {
								//document.write(strCLodopUpdate);
								layer.alert(strCLodopUpdate, {
									btn: [],
									icon: 0,
									title: "提示"
								});
							} else {
								//document.documentElement.innerHTML = strCLodopUpdate + document.documentElement.innerHTML;
								layer.alert(strCLodopUpdate, {
									btn: [],
									icon: 0,
									title: "提示"
								});
							}
						};
						if (oEMBED && oEMBED.parentNode)
							oEMBED.parentNode.removeChild(oEMBED);
						if (oOBJECT && oOBJECT.parentNode)
							oOBJECT.parentNode.removeChild(oOBJECT);
					};
				} else {
					//=====如果页面有Lodop就直接使用，没有则新建:==========
					if (oOBJECT != undefined || oEMBED != undefined) {
						if (isIE) {
							this.CLODOP = oOBJECT;
						} else {
							this.CLODOP = oEMBED;
						}
					} else if (CreatedOKLodop7766 == null) {
						this.CLODOP = document.createElement("object");
						this.CLODOP.setAttribute("width", 0);
						this.CLODOP.setAttribute("height", 0);
						this.CLODOP.setAttribute("style", "position:absolute;left:0px;top:-100px;width:0px;height:0px;");
						if (isIE) {
							this.CLODOP.setAttribute("classid", "clsid:2105C259-1E0C-4534-8141-A753534CB4CA");
						} else {
							this.CLODOP.setAttribute("type", "application/x-print-lodop");
						}
						document.documentElement.appendChild(this.CLODOP);
						CreatedOKLodop7766 = this.CLODOP;
					} else {
						this.CLODOP = CreatedOKLodop7766;
					}
					//=====Lodop插件未安装时提示下载地址:==========
					if ((this.CLODOP == null) || (typeof(this.CLODOP.VERSION) == "undefined")) {
						if (navigator.userAgent.indexOf('Chrome') >= 0)
							//document.documentElement.innerHTML = strHtmChrome + document.documentElement.innerHTML;
							layer.alert(strHtmChrome, {
								btn: [],
								icon: 0,
								title: "提示"
							});
						if (navigator.userAgent.indexOf('Firefox') >= 0)
							layer.alert(strHtmFireFox, {
								btn: [],
								icon: 0,
								title: "提示"
							});
						if (is64IE) {
							layer.alert(strHtm64_Install, {
								btn: [],
								icon: 0,
								title: "提示"
							});
						} else if (isIE) {
							layer.alert(strHtmInstall, {
								btn: [],
								icon: 0,
								title: "提示"
							});
						} else {
							layer.alert(strHtmInstall, {
								btn: [],
								icon: 0,
								title: "提示"
							});
						}
						return this.CLODOP;
					};
				};
				if (this.CLODOP.VERSION < "6.2.1.8") {
					if (needCLodop()) {
						layer.alert(strCLodopUpdate, {
							btn: [],
							icon: 0,
							title: "提示"
						});
					} else if (is64IE) {
						layer.alert(strHtm64_Update, {
							btn: [],
							icon: 0,
							title: "提示"
						});
					} else if (isIE) {
						layer.alert(strHtmUpdate, {
							btn: [],
							icon: 0,
							title: "提示"
						});
					} else {
						layer.alert(strHtmUpdate, {
							btn: [],
							icon: 0,
							title: "提示"
						});
					}
					return this.CLODOP;
				};
				//===如下空白位置适合调用统一功能(如注册语句、语言选择等):===
				this.CLODOP.SET_LICENSES("快搭科技(上海)有限公司", "B2FF47D5AB0D51900007D05CDEDE7E65", "", "");
				//===========================================================
				return this.CLODOP;
			} catch (err) {
				alert("getLodop出错:" + err);
			};
		}
		/* Lodop 官方代码块 - END*/
		//====判断是否需要安装CLodop云打印服务器:====
		function needCLodop() {
			try {
				var ua = navigator.userAgent;
				if (ua.match(/Windows\sPhone/i) != null)
					return true;
				if (ua.match(/iPhone|iPod/i) != null)
					return true;
				if (ua.match(/Android/i) != null)
					return true;
				if (ua.match(/Edge\D?\d+/i) != null)
					return true;

				var verTrident = ua.match(/Trident\D?\d+/i);
				var verIE = ua.match(/MSIE\D?\d+/i);
				var verOPR = ua.match(/OPR\D?\d+/i);
				var verFF = ua.match(/Firefox\D?\d+/i);
				var x64 = ua.match(/x64/i);
				if ((verTrident == null) && (verIE == null) && (x64 !== null)) {
					return true;
				} else if (verFF !== null) {
					verFF = verFF[0].match(/\d+/);
					if ((verFF[0] >= 42) || (x64 !== null))
						return true;
				} else if (verOPR !== null) {
					verOPR = verOPR[0].match(/\d+/);
					if (verOPR[0] >= 32)
						return true;
				} else if ((verTrident == null) && (verIE == null)) {
					var verChrome = ua.match(/Chrome\D?\d+/i);
					if (verChrome !== null) {
						verChrome = verChrome[0].match(/\d+/);
						if (verChrome[0] >= 42)
							return true;
					};
				};
				return false;
				// return true; // 强制使用 C-Lodop
			} catch (err) {
				return true;
			};
		};
	};

})(jQuery);
